package com.hk.mybatis.query;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.ArrayList;
import java.util.List;

/**
 * 分页和排序工具类
 */
public class PageAndSortUtil {

    /**
     * 创建排序对象
     *
     * @param orderBys @link List<OrderBy>} 排序条件
     * @return {@link OrderItem} 排序对象
     */
    public static List<OrderItem> buildOrder(List<OrderBy> orderBys) {
        if ((orderBys == null) || (orderBys.isEmpty())) {
            return null;
        }
        List<OrderItem> orders = new ArrayList<>();
        for (OrderBy orderBy : orderBys) {
            if (orderBy == null) {
                continue;
            }
            orders.add(orderBy.getOrderBy());
        }
        return orders;
    }

    /**
     * 创建分页和排序对象
     *
     * @param pageNumber @link int} 当前页码
     * @param pageSize   @link int} 每页条数
     * @param orderBys   @link List<OrderBy>} 排序条件
     * @return 分页和排序对象
     */
    public static <T> IPage<T> buildPageAndSort(int pageNumber, int pageSize, List<OrderBy> orderBys) {
        final Page<T> page = Page.of(pageNumber, pageSize);
        if ((orderBys == null) || (orderBys.isEmpty())) {
            return page;
        }

        List<OrderItem> orders = new ArrayList<>();
        for (OrderBy orderBy : orderBys) {
            if (orderBy == null) {
                continue;
            }
            orders.add(orderBy.getOrderBy());
        }
        page.setOrders(orders);
        return page;
    }
}
